<?php
import($GLOBALS['spConfig']['controller_path'] . '/general.php');
/**
 * 首页管理控制器
 * @author Fosf
 * @version 1.0
 * @created 2011-04-11
 */
class main extends general
{
    function __construct()
    { // 公用
        parent::__construct(); // 这是必须的
    }

    function index()
    {
        // 这里是首页
        $this->title = SITENAME;
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->ishome = true;

        if (HOME_LHT_NUM_TYPE == 'True') {
            $adObj = spClass('adModel');
            $adlist = $adObj->get_ad_list(HOME_LHT_NUM);
            $this->adlist = $adlist;
            $this->$i = 1;
        }

        if (HOME_PRODUCTS_TYPE == 'True') {
            $homeproducts=spClass('productsModel')->products_random(null,HOME_PRODUCTS,HOME_PRODUCTS_ORDER);
            $this->homeproducts=$homeproducts;
        }

        if (HOME_NEWS_TYPE == 'True') {
            $news = spClass("newsModel");
            $newtopnews = $news->get_news_list('', HOME_NEWS);
            $this->newtopnews = $newtopnews;
        }
        $this->display("index/index_main.html");
    }

    function PasswordForgotten()
    {
        $action = $this->spArgs('action');
        $email = $this->spArgs('email_address');
        $mailsend = spClass('email_templateModel');

        if ($action == 'process') {

            if ($mailsend->isemail($email)) {
                if (spClass('customersModel')->emailExist($email)) {
                    $mailpass_view = md5($email . time() . 'fosf');
                    $mailpassdata = array(
                        'mailpass_view' => $mailpass_view,
                        'mailpass_time' => time() + 86400,
                        'customers_id' => '',
                        'email' => $email);
                    $passmailurl = WEBURL . WEBDIR . 'main/PasswordReset.html?code=' . $mailpass_view;
                    if (spClass('mailpassModel')->Create($mailpassdata)) {
                        //date_default_timezone_set('America/Toronto');
                        $mail = spClass('email_templateModel');

                        //1为注册成功模板

                        $str = $mail->Detail(2);
                        //dump($str);
                        $body = $mail->mail_replace($str['content'], $email, $fullname);
                        $body = str_replace('#PASSMAILURL#', $passmailurl, $body);
                        //echo $body;
                        //exit;
                        if ($mail->Sendmail($email, $email, REPLYEMAIL, STORENAME, T('SUBJECT_MAILPASS'),
                            $body)) {
                            $sendmailok = true;
                        }
                    }


                    $this->successmail = T('A new password has been sent to your email address.');


                } else {
                    $this->errormail = T('Error: The Email Address was not found in our records; please try again.');
                }
            } else {
                $this->errormail = T('Error: The Email Address was not found in our records; please try again.');
            }
        }
        $this->action = $action;
        $this->title = "Password Forgotten :" . SITENAME;
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_password_forgotten.html");
    }

    function PasswordReset()
    {

        $code = $this->spArgs("code");
        $email_address = $this->spArgs('email_address');
        $password = $this->spArgs('password');
        $confirmation = $this->spArgs('confirmation');

        //
        if ($this->spArgs('action') == 'process') {
            if ($code <> '') {
                $mailpass = spClass('mailpassModel');
                $maildata = array('mailpass_view' => $code, 'email' => $email_address);
                $aaa = $mailpass->find($maildata);
                //exit;
                if ($aaa) {
                    $customers = spClass('customersModel');

                    if ($password == $confirmation) {
                        $pass = $customers->editmailpass($email_address, $password);
                        if ($pass) {
                            $this->pass = 'true';
                            $this->passinfo = T('Your password has been successfully updated.');
                            $mailpass->delete($maildata);
                        } else {
                            $this->pass = 'false';
                            $this->passinfo = T('Your Current Password did not match the password in our records. Please try again.');
                        }
                    } else {
                        $this->pass = 'false';
                        $this->passinfo = T('The Password Confirmation must match your Password.');
                    }

                } else {
                    $this->pass = 'false';
                    $this->passinfo = T('Your Current Password did not match the password in our records. Please try again.');
                }

            } else {
                $this->pass = 'false';
                $this->passinfo = T('Web site has expired, or mistake');
            }
            $this->isinfo = true;
        }

        $this->code = $code;
        $this->title = "Password Reset :" . SITENAME;
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_password_reset.html");
    }
    function Facebook()
    {
        if (FACEBOOK_TYPE == 'True') {
            //dump($this->spArgs());
            //exit;

            $user = $this->facebook->getUser();
            if ($user) {
                try {
                    // Proceed knowing you have a logged in user who's authenticated.
                    $user_profile = $this->facebook->api('/me');


                    $facebook_id = $user_profile[id];
                    $firstname = $user_profile[first_name];
                    $lastname = $user_profile[last_name];
                    $street_address = '';
                    $suburb = '';
                    $city = '';
                    $state = '';
                    $postcode = '';
                    $zone_country_id = '';
                    $telephone = '';
                    $email_address = $user_profile[email];
                    $password = generate_rand(10);
                    $data_customers = array(
                        'customers_firstname' => $firstname,
                        'customers_lastname' => $lastname,
                        'customers_email_address' => $email_address,
                        'customers_telephone' => $telephone,
                        'customers_pass' => $password,
                        'no_customers' => 1,
                        'facebook_id' => $facebook_id,
                        'customers_adddate' => time(),
                        'customers_lastlogin' => time());
                    //dump($data_customers);
                    //exit;
                    $data_address = array(
                        'customers_firstname' => $firstname,
                        'customers_lastname' => $lastname,
                        'entry_street_address' => $street_address,
                        'entry_suburb' => $suburb,
                        'entry_postcode' => $postcode,
                        'entry_city' => $city,
                        'entry_state' => $state,
                        'entry_country_id' => $zone_country_id);
                    $objcustomers = spClass("customersModel");
                    $customerstype = $objcustomers->create_account($data_customers, $data_address);
                    //dump($customerstype);
                    //exit;
                    switch ($customerstype[type]) {
                        case 1:
                            //用户名存在，就登入合并购物车
                            $loginok = $objcustomers->loingok($email_address);
                            //dump($loginok);
                            //exit;
                            if ($loginok)
                                $objcustomers->CartHB();
                            if ($_SESSION['HB']) //如果存在合并就跳到购物车
                                {
                                $clienturl = WEBURL . WEBDIR . 'shopping_cart.html';
                            } else {
                                $clienturl = WEBURL . WEBDIR . 'index.html';
                            }
                            break;
                        case 2:
                            $clienturl = WEBURL . WEBDIR . 'address_book_process.html?edit=' . $customerstype[user][addressid];
                            break;
                        case 3:
                            $clienturl = WEBURL . WEBDIR . 'address_book_process.html?edit=' . $customerstype[user][addressid];
                            break;
                        default:
                            $clienturl = WEBURL . WEBDIR . 'address_book_process.html?edit=' . $customerstype[user][addressid];
                    }
                    $this->jump($clienturl);
                }
                catch (FacebookApiException $e) {
                    error_log($e);
                    $user = null;
                }
                //dump($user_profile);

            }

        }
    }
    function Flogin()
    {
        $this->isFlogin = true;
        $this->title = "Login";
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $_SESSION['request_uri'] = WEBURL . WEBDIR;
        $returnurl = $this->spArgs('returnurl', spUrl('main', 'index'));
        $this->returnurl = $returnurl;
        $this->display("Fbox/Fbox.html");
    }
    function Login()
    {
        $this->title = "Login";
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $_SESSION['request_uri'] = WEBURL . WEBDIR;
        $returnurl = $this->spArgs('returnurl', spUrl('main', 'index'));
        if ($action = $this->spArgs('action') == "process") {
            //dump($this->spArgs());
            $type = $this->spArgs('type', false);
            $objcustomers = spClass("customersModel");
            $email_address = $this->spArgs("email_address");
            $password = $this->spArgs("password");
            // 使用spVerifier进行第一次检查
            $rows = array('customers_email_address' => $email_address);
            $results = $objcustomers->spVerifier($rows);
            if (false == $results) { // 当spVerifier返回false的时候，则是表示已经通过验证，数据是合格的

                // 使用lib_user类中我们新建的userlogin方法来验证用户名和密码
                if (false == $objcustomers->customerslogin($email_address, $password)) {
                    // 登录失败，提示后跳转回登录页面
                    if (!$type)
                        $this->jump(spUrl('main', 'Login')); //"用户名/密码错误，请重新输入！"
                    $status = 'n';
                    $msg = 'Username/password mistake';
                } else {
                    if ($objcustomers->CartHB()) {
                        if (!$type)
                            $this->jump(spUrl('main', 'ShoppingCart')); //有记录，返回合并后的购物车！
                        $status = 'y';
                        $msg = 'Login success';
                        $url = spUrl('main', 'ShoppingCart');
                    } else {
                        if (!$type)
                            $this->jump($returnurl); //无记录，反回登入前的页面！
                        $status = 'y';
                        $msg = 'Login success';
                        $url = $returnurl;
                    }
                }
            } else {
                // $results不是false，所以没有通过验证，错误信息是$results
                // dump($results);
                foreach ($results as $item) { // 开始循环错误信息的规则，这里只有用户名
                    // 每一个规则，都有可能返回多个错误信息，所以这里我们也循环$item来获取多个信息
                    foreach ($item as $msg) {
                        // 虽然我们使用了循环，但是这里我们只需要第一条出错信息就行。
                        // 所以取到了第一条错误信息的时候，我们使用$this->error来提示并跳转
                        if (!$type)
                            $this->error($msg, spUrl('main', 'Login'));
                        $status = 'n';
                        $msg = 'Username/password mistake';
                    }
                }
            }
            $result = array(
                'status' => $status,
                'info' => $msg,
                'url' => $url,
                );
            echo json_encode($result);
        } else {
            $this->returnurl = $returnurl;
            $this->display("index/index_login.html");
        }

    }

    /**
     * 检测EMAIL是否存在
     */
    function checkemail()
    {
        $email = $this->spArgs('param');
        if ($email <> '') {
            $request = spClass('customersModel')->emailExist($email);
            if ($request) {
                echo T('User already exists!');
            } else {
                echo "y";
            }
        } else {
            echo "Please enter your email address!";
        }

    }
    //创建顾客信息
    function CreateAccount()
    {
        $this->title = "Create an Account";
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        //$this->country = $this->country_en();

        if ($action = $this->spArgs('action') == "process") {

            $firstname = $this->spArgs("firstname");
            $lastname = $this->spArgs("lastname");
            $street_address = $this->spArgs("street_address");
            $suburb = $this->spArgs("suburb");
            $city = $this->spArgs("city");
            $state = $this->spArgs("state");
            $postcode = $this->spArgs("postcode");
            $zone_country_id = $this->spArgs("zone_country_id");
            $telephone = $this->spArgs("telephone");
            $email_address = $this->spArgs("email_address");
            $password = $this->spArgs("password");
            $confirmation = $this->spArgs("confirmation");

            $msg = T('User already exists!');
            $status = '1';

            if ($password != '' && $password === $confirmation) {
                $data_customers = array(
                    'customers_firstname' => $firstname,
                    'customers_lastname' => $lastname,
                    'customers_email_address' => $email_address,
                    'customers_telephone' => $telephone,
                    'customers_pass' => $password,
                    'customers_adddate' => time(),
                    'customers_lastlogin' => time());
                $data_address = array(
                    'customers_firstname' => $firstname,
                    'customers_lastname' => $lastname,
                    'entry_street_address' => $street_address,
                    'entry_suburb' => $suburb,
                    'entry_postcode' => $postcode,
                    'entry_city' => $city,
                    'entry_state' => $state,
                    'entry_country_id' => $zone_country_id);
                $objcustomers = spClass("customersModel");
                $customerstype = $objcustomers->create_account($data_customers, $data_address);

                $msg = $customerstype['msg'];
                $status = $customerstype['type'];
            }

            $result = array(
                'status' => $status,
                'info' => $msg,
                );
            echo json_encode($result);
        } else {
            $this->display("index/index_create_account.html");
        }
    }

    //创建顾客信息
    function NoAccount()
    {
        $this->title = "Create an Account";
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        //$this->country = $this->country_en();

        if ($action = $this->spArgs('action') == "process") {
            //dump($this->spArgs());
            $firstname = $this->spArgs("firstname");
            $lastname = $this->spArgs("lastname");
            $street_address = $this->spArgs("street_address");
            $suburb = $this->spArgs("suburb");
            $city = $this->spArgs("city");
            $state = $this->spArgs("state");
            $postcode = $this->spArgs("postcode");
            $zone_country_id = $this->spArgs("zone_country_id");
            $telephone = $this->spArgs("telephone");
            $email_address = $this->spArgs("email_address");
            $password = generate_rand(10);
            $data_customers = array(
                'customers_firstname' => $firstname,
                'customers_lastname' => $lastname,
                'customers_email_address' => $email_address,
                'customers_telephone' => $telephone,
                'customers_pass' => $password,
                'no_customers' => 1,
                'customers_adddate' => time(),
                'customers_lastlogin' => time());
            $data_address = array(
                'customers_firstname' => $firstname,
                'customers_lastname' => $lastname,
                'entry_street_address' => $street_address,
                'entry_suburb' => $suburb,
                'entry_postcode' => $postcode,
                'entry_city' => $city,
                'entry_state' => $state,
                'entry_country_id' => $zone_country_id);
            $objcustomers = spClass("customersModel");
            $customerstype = $objcustomers->create_account($data_customers, $data_address);

            $msg = $customerstype['msg'];
            $status = $customerstype['type'];
            $result = array(
                'status' => $status,
                'info' => $msg,
                );
            echo json_encode($result);

        } else {

            $this->title = "Billing Information";
            $this->keywords = KEYWORDS;
            $this->description = DESCRIPTION;
            $this->display("index/index_noaccount.html");
        }
    }


    function CreateAccountSuccess()
    {
        $this->title = "Success";
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        //$u=spClass('customersModel')->spLink()->find('custmoers_id='.$this->userrarr);
        // dump();
        $address = spClass('address_bookModel')->find('address_book_id=' . $this->
            userarr['customers_default_address_id']);
        $this->add = $address;
        $this->display("index/index_create_account_success.html");
    }

    function AccountHistory()
    {
        $this->account = true;
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }
        $orderlist = spClass('orderModel')->findAll('customers_id=' . $this->userarr['customers_id']);
        foreach ($orderlist as $k => $v) {
            $conditions = array('orders_id' => $v['orders_id']); // 条件是同样的
            $orderlist[$k]['count'] = spClass('orders_productsModel')->findCount($conditions); // 使用了findCount
            $orderlist[$k]['orders_status'] = $this->forstatus($v['orders_status']);

        }

        $this->orderlist = $orderlist;
        //dump($orderlist);
        $this->title = T("My Order History");
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_account_history.html");
    }

    function AccountHistoryInfo()
    {
        $this->account = true;
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }

        $orders_id = $this->spArgs('order_id');

        if ($orders_id == '') {
            $this->jump('account.html');
        }
        $order = spClass('orderModel')->find('orders_id=' . $orders_id);
        $conditions = array('orders_id' => $order['orders_id']);

        $orderslist = spClass('orders_productsModel')->findAll($conditions,
            'orders_id desc');
        $conditions2 = array('orders_sn' => $order['orders_sn']);
        $orders_status = spClass('orders_status_historyModel')->findAll($conditions2);

        foreach ($orders_status as $k => $v) {
            $orders_status[$k]['orders_status_id'] = $this->forstatus($v['orders_status_id']);
        }
        //dump($orderslist);
        $this->ordersstatus = $orders_status;
        $this->order = $order;
        $this->orderslist = $orderslist;

        $this->title = T("Order Information");
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_account_history_info.html");
    }
    /**
     * 根据状态ID返回相关数据
     */
    function forstatus($orders_status_id)
    {
        foreach ($this->orders_status as $k => $v) {
            if ($v['orders_status_id'] == $orders_status_id) {
                return $v['orders_status_name'];
            }
        }
        return false;
    }

    function Account()
    {
        $this->account = true;
        if ($this->userarr['customers_id'] == '') {
            $this->jump('login.html');
        }
        $orderlist = spClass('orderModel')->findAll('customers_id=' . $this->userarr['customers_id'],
            'orders_id desc', null, 3);

        foreach ($orderlist as $k => $v) {
            $orderlist[$k]['orders_status'] = $this->forstatus($v['orders_status']);
        }

        //echo $this->forcount(20);
        //dump($orderlist);
        $this->orderlist = $orderlist;
        //dump($orderlist);
        $this->title = T("My account");
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_account.html");
    }

    function AccountEdit()
    {
        $this->account = true;
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }
        $account = $this->userarr;
        if ($this->spArgs('action') == "process") {
            $firstname = $this->spArgs("firstname");
            $lastname = $this->spArgs("lastname");

            //$telephone = $this->spArgs("telephone");
            $status = 1;
            $msg = 'Submit failure';
            if ($firstname <> '' && $lastname <> '') {
                //$email_address = $this->spArgs("email_address");
                $dataform = array(
                    'customers_firstname' => $firstname,
                    'customers_lastname' => $lastname,
                    //'customers_telephone' => $telephone,
                    );
                spClass('customersModel')->update('customers_id=' . $account['customers_id'], $dataform);
                $request = spClass('customersModel')->find('customers_id=' . $account['customers_id']);
                $data = serialize($request);
                spClass("customersSession")->write($data, time());
                $status = 2;
                $msg = 'Submit success!';
            }
            $result = array(
                'status' => $status,
                'info' => $msg,
                );
            echo json_encode($result);
        } else {
            $this->title = T("My Account Information");
            $this->keywords = KEYWORDS;
            $this->description = DESCRIPTION;

            $account = spClass('customersModel')->find('customers_id=' . $account['customers_id']);
            //dump($account);
            $this->account = $account;
            $this->display("index/index_account_edit.html");
        }
    }
    function AccountPassword()
    {
        $this->account = true;
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }

        $account = $this->userarr;
        if ($this->spArgs('action') == "process") {
            $customers = spClass('customersModel');

            $oldpass = $this->spArgs('password_current');
            $newpass = $this->spArgs('password_new');
            $newpass2 = $this->spArgs('password_confirmation');
            if ($newpass == $newpass2) {
                $pass = $customers->editpass($this->userarr['customers_id'], $oldpass, $newpass);
                if ($pass) {
                    $status = 'y';
                    $msg = T('Your password has been successfully updated.');
                } else {
                    $status = 'n';
                    $msg = T('Your Current Password did not match the password in our records. Please try again.');
                }
            } else {
                $status = 'n';
                $msg = T('The Password Confirmation must match your Password.');
            }

            $result = array(
                'status' => $status,
                'info' => $msg,
                );
            echo json_encode($result);
            exit;
        }

        $this->title = T("My Password");
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_account_password.html");

    }
    /**
     * 客户地址
     */
    function AddressBook()
    {
        $this->account = true;
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }

        $address = spClass('address_bookModel')->find('address_book_id=' . $this->
            userarr['customers_default_address_id']);
        $address['entry_country_id'] = $this->forcount($address['entry_country_id']);
        $addarr = spClass('address_bookModel')->findAll('customers_id=' . $this->
            userarr['customers_id']);
        //dump($addarr);
        foreach ($addarr as $k => $v) {
            //echo $v['entry_country_id'];
            $addarr[$k]['entry_country_id'] = $this->forcount($v['entry_country_id']);
            //echo $addarr[$k]['entry_country_id'];
        }
        //dump($addarr);
        $this->addarr = $addarr;
        $this->add = $address;

        $this->title = T("Address Book");
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_address_book.html");
    }
    /**
     * 修改客户地址
     */
    function AddressBookProcess()
    {
        $this->account = true;
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }

        $customers = spClass('customersModel');
        $addressobj = spClass('address_bookModel');
        $sessionobj = spClass("customersSession");
        $addid = $this->spArgs('edit');
        $delete = $this->spArgs('delete', 0);
        $customersid = $this->userarr['customers_id'];
        $primary = $this->spArgs('primary');
        $action = $this->spArgs('action');
        $telephone = $this->spArgs("telephone");
        
        if ($delete > 0) {
            $addressobj->delete('address_book_id=' . $delete);
            $this->jump(spUrl('main', 'AddressBook'));
        }

        $firstname = $this->spArgs("firstname");
        $lastname = $this->spArgs("lastname");
        $street_address = $this->spArgs("street_address");
        $suburb = $this->spArgs("suburb");
        $city = $this->spArgs("city");
        $state = $this->spArgs("state");
        $postcode = $this->spArgs("postcode");
        $telephone = $telephone;
        $zone_country_id = $this->spArgs("zone_country_id");
        if ($action <> '') {

            $dataadd = array(
                'customers_id' => $customersid,
                'customers_firstname' => $firstname,
                'customers_lastname' => $lastname,
                'entry_street_address' => $street_address,
                'entry_suburb' => $suburb,
                'customers_telephone' => $telephone,
                'entry_city' => $city,
                'entry_state' => $state,
                'entry_country_id' => $zone_country_id);
        }

        if ($action == 'add') {

            $addid = $addressobj->create($dataadd); //修改顾客数据的默认地址ID
            if ($primary == 'on') {
                $data['customers_default_address_id'] = $addid;
                $customers->update('customers_id=' . $customersid, $data);
                $request = $customers->find('customers_id=' . $customersid);
                $data = serialize($request);
                $sessionobj->write($data, time());
            }
            $result = array(
                'status' => 2,
                'info' => '',
                );
            echo json_encode($result);
            exit;

        }
        if ($action == 'update') {
            $addressobj->update('address_book_id=' . $addid, $dataadd); //修改顾客数据的默认地址ID
            if ($primary == 'on') {
                $data['customers_default_address_id'] = $addid;
                $customers->update('customers_id=' . $customersid, $data);
                $request = $customers->find('customers_id=' . $customersid);

                $data = serialize($request);
                //dump($request);
                $sessionobj->write($data, time());
            }
            $result = array(
                'status' => 2,
                'info' => '',
                );
            echo json_encode($result);
            exit;
        }

        if ($addid <> '') {
            $this->action = 'update';
            $address = $addressobj->find('address_book_id=' . $addid);
            //dump($address);
        } else {
            $this->action = 'add';
        }
        //        $this->country = $this->country_en();
        $this->add = $address;
        $this->title = T("Update Entry");
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;


        $this->display("index/index_address_book_process.html");

    }

    function CheckoutShippingAddress()
    {
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }
        $this->isCurrencies = true;
        $customers = spClass('customersModel');
        $addressobj = spClass('address_bookModel');
        $sessionobj = spClass("customersSession");
        $customersid = $this->userarr['customers_id'];

        //dump($this->spArgs());
        $address_book_id = $this->spArgs('address_book_id');
        $firstname = $this->spArgs("firstname");
        $lastname = $this->spArgs("lastname");
        $street_address = $this->spArgs("street_address");
        $suburb = $this->spArgs("suburb");
        $city = $this->spArgs("city");
        $state = $this->spArgs("state");
        $postcode = $this->spArgs("postcode");
        $telephone = $this->spArgs("telephone");
        $zone_country_id = $this->spArgs("zone_country_id");

        $address = $this->spArgs('address');
        $s = $this->spArgs('s');

        if ($address_book_id <> '' && $address <> '') {

            if ($address_book_id == $address) {
                $dataadd = array(
                    'customers_id' => $customersid,
                    'customers_firstname' => $firstname,
                    'customers_lastname' => $lastname,
                    'entry_street_address' => $street_address,
                    'entry_suburb' => $suburb,
                    'entry_postcode' => $postcode,
                    'entry_city' => $city,
                    'entry_state' => $state,
                    'customers_telephone' => $telephone,
                    'entry_country_id' => $zone_country_id);

                $addressobj->update('address_book_id=' . $address_book_id, $dataadd); //修改顾客数据的默认地址ID

            } else {
                $data['customers_default_address_id'] = $address;
                $customers->update('customers_id=' . $customersid, $data);
            }

            $request = $customers->find('customers_id=' . $customersid);
            $data = serialize($request);
            $sessionobj->write($data, 1440);
            if ($s == 'payment') {
                $this->jump(spUrl('main', 'CheckoutPayment'));
            }
            $this->jump(spUrl('main', 'CheckoutShipping'));

        }


        //        $this->country = $this->country_en();
        $address = spClass('address_bookModel')->find('address_book_id=' . $this->
            userarr['customers_default_address_id']);
        $addarr = spClass('address_bookModel')->findAll('customers_id=' . $this->
            userarr['customers_id']);
        //dump($address);
        $address['entry_country_id2'] = $this->forcount($address['entry_country_id']);
        //$address['entry_country_id']=$this->forcount($address['entry_country_id']);
        //dump($address);
        foreach ($addarr as $k => $v) {
            $addarr[$k]['entry_country_id'] = $this->forcount($v['entry_country_id']);
        }

        $this->addarr = $addarr;
        $this->add = $address;
        $this->s = $s;
        $this->title = T("Change Shipping Address");
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_checkout_shipping_address.html");
    }

    // 退出登录
    function logout()
    {
        $_SESSION = array();
        if (isset($_COOKIE['abcsession_id'])) {
            spClass('customersSession')->del();
        }
        if (isset($_COOKIE['CARTSESSION_ID'])) {
            spClass('cartSession')->del();
        }


        setcookie("CARTSESSION_ID", "", time() - 86400, WEBDIR);
        setcookie("abcsession_id", "", time() - 86400, WEBDIR);

        $returnurl = $this->spArgs('returnurl', spUrl('main', 'index'));
        // 跳转回首页
        $this->jump($returnurl); // 已退出，返回首页！
    }

    //购物车
    function ShoppingCart()
    {
        $this->isCurrencies = true;
        $this->isShopping = true;
        $cart = $this->cartarr;
        $customers_basket = spClass('customers_basketModel');
        $customers_id = $this->userarr['customers_id']; //此数据来自初始化处
        if (isset($_SESSION['paypal_EC']['token'])) {
            unset($_SESSION['paypal_EC']);
            unset($_SESSION['reshash']);
            unset($_SESSION['reshash_check']);
            unset($_SESSION['payment_step']);
        }
        if ($action = $this->spArgs("action") == "update_product") {
            //dump($this->spArgs());

            $cart_quantity = $this->spArgs('cart_quantity');
            $cartid = $this->spArgs('cartid');
            $cart_delete = $this->spArgs('cart_delete');
            //dump($cart_delete);
            //exit;
            //勾选批量删除
            if (count($cart_delete) > 0 && is_array($cart_delete)) {
                foreach ($cart_delete as $key => $val) {
                    $id = (int)$val;
                    //$quantity=(int)$cart_delete[$i];

                    if ($customers_id <> '') {
                        $customers_basket->delCart($customers_id, $id); // 删除记录
                    } else {
                        $cart->ModifyCart($id, 0, 3);
                    }
                    $i++;
                }
                $this->jump(spUrl('main', 'ShoppingCart'));
            }
            //指量修改
            $i = 0;
            if (is_array($cartid)) {
                foreach ($cartid as $key => $val) {
                    $id = (int)$val;
                    $quantity = (int)$cart_quantity[$i];
                    if ($customers_id <> '') {
                        $data = array('customers_basket_quantity' => $quantity);
                        $customers_basket->updateCart($customers_id, $id, $data); // 修改记录
                    } else {
                        $cart->ModifyCart($id, $quantity, 2);
                    }
                    $i++;
                }
            }
            $this->jump(spUrl('main', 'ShoppingCart'));
        }

        //删除单个商品
        if ($action = $this->spArgs("action") == "remove_product") {
            $cartid = $this->spArgs('cartid');
            $id = (int)$cartid;
            if ($customers_id <> '') {
                $customers_basket->delCart($customers_id, $id); // 删除记录
            } else {
                $cart->ModifyCart($id, 0, 3);
            }
            $this->jump(spUrl('main', 'ShoppingCart'));
            //exit;
        }

        $this->title = T("The Shopping Cart") . ":" . SITENAME;
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        if ($_SESSION['HB'])
            $this->HB = true;
        $_SESSION['HB'] = '';
        $tmpArray = array();
        $tmpArray = $cart->CartView(); // 防止在此之前数据被外部修改
        //dump($tmpArray);
        $outArray = array(); //一维数组
        // price1 是产品1的总价格
        // price2 是产品2的总价格
        // price3 是产品3的总价格
        // count  是产品的总数量
        $i = 0;
        if (is_array($tmpArray['id'])) {
            foreach ($tmpArray['id'] as $key => $val) {
                $product = spClass("productsModel")->Detail($tmpArray['pid'][$key]);
                $outArray[$i]['cartid'] = $tmpArray['id'][$key];
                $outArray[$i]['pid'] = $tmpArray['pid'][$key];
                $outArray[$i]['name'] = $tmpArray['name'][$key];
                $outArray[$i]['image'] = $product['products_image'];
                $outArray[$i]['size'] = $tmpArray['size'][$key];
                $outArray[$i]['price1'] = $tmpArray['price1'][$key];
                $outArray[$i]['price2'] = $tmpArray['price2'][$key];
                $outArray[$i]['other'] = $tmpArray['other'][$key];
                $priceview = Get_price(array(
                    'pid' => $tmpArray['pid'][$key],
                    'price' => $tmpArray['price1'][$key],
                    'price2' => $tmpArray['price2'][$key],
                    'strtype' => 1,
                    'GDcart' => 5));
                $outArray[$i]['Total'] = $priceview * $tmpArray['count'][$key];
                $outArray[$i]['count'] = $tmpArray['count'][$key];
                $i++;
            }
        }
        //dump($outArray);
        $this->tmpCaryarray = $outArray;
        $this->display("index/index_shopping_cart.html");
    }

    //付款去
    function CheckoutShipping()
    {
        //$cart = $this->cartarr;
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login').'?returnurl='.spUrl('main', 'CheckoutShipping'));
        }
        $this->isCurrencies = true;
        //dump($this->spArgs());
        if ($action = $this->spArgs('action') == 'process') {
            $shipping = $this->spArgs('shipping', 0);
            if ($shipping <> $_SESSION[shipping]) {
                unset($_SESSION['payment_step']);
            }
            $comments = urldecode(strip_tags($this->spArgs('comments')));
            //setcookie('comments', $comments);
            $_SESSION[comments] = $comments;
            $_SESSION[shipping] = $shipping;
            //setcookie('shipping', $shipping);

            $this->jump(spUrl('main', 'CheckoutPayment'));
        }

        $customersid = $this->userarr['customers_id'];
        if ($customersid <> '') {
            $address = spClass('address_bookModel')->find('address_book_id=' . $this->
                userarr['customers_default_address_id']);
            $address['entry_country_id'] = $this->forcount($address['entry_country_id']);
            $this->add = $address;
        }
        $this->title = T("Step 2 of 5 - Delivery Information") . ":" . SITENAME;
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;


        $this->display("index/index_checkout_shipping.html");
    }

    //付款方式
    function CheckoutPayment()
    {
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login').'?returnurl='.spUrl('main', 'CheckoutPayment'));
        }
        $customersid = $this->userarr['customers_id'];
        $this->isCurrencies = true;

        $address = spClass('address_bookModel')->return_address($this->userarr['customers_default_address_id']);
        $address['entry_country_id'] = $this->forcount($address['entry_country_id']);
        $this->add = $address;
        foreach ($this->shippingarr as $k => $v) {
            if ($_SESSION[shipping] == $v[0]) {
                $this->selectshipping = $v;
                $shippingselect = $v;
            }
        }
        //dump($selectshipping);
        if ($action = $this->spArgs('action') == 'process') {

            $comments = urldecode(strip_tags($this->spArgs('comments')));
            $payment = $this->spArgs('payment', $_SESSION['payment']);
            $_SESSION['comments'] = $comments;
            //setcookie('comments', $comments);
            $_SESSION['payment'] = $payment;
            //setcookie('payment', $payment);
            $orders_id = $_SESSION['orders_id'];
            //$orders_id= $_COOKIE['orders_id'];


            //区分选择的支付方式
            if ($payment == RPPAY_CODE) {
                $status_id = RPPAY_ORDER_STATUS_ID;
            }
            if ($payment == RPPAY_M_CODE) {
                $status_id = RPPAY_M_ORDER_STATUS_ID;
            }
            if ($payment == IPS_CODE) {
                $status_id = IPS_ORDER_STATUS_ID;
            }
            if ($payment == PAYPAL_EC_CODE) {
                $status_id = PAYPAL_EC_ORDER_STATUS_ID;
            }
            if ($payment == WESTERNUNION_CODE) {
                $status_id = WESTERNUNION_ORDER_STATUS_ID;
                $Discount = WESTERNUNION_MONEY;
            }
            if ($payment == ALIPAY_CODE) {
                $status_id = ALIPAY_ORDER_STATUS_ID;
            }
            $Discount = ($Discount) ? Get_Discount(array('Discount' => $Discount, 'item' =>
                    $this->total['count'])) : 0;
            if ($_SESSION['payment_step'] == 'checkout_payment') {
                if ($_SESSION['comments'] <> '')
                    $data2 = array(
                        'orders_sn' => $_SESSION['orders_sn'],
                        'orders_status_id' => PAYPAL_EC_ORDER_STATUS_ID,
                        'comments' => $_SESSION['comments'],
                        'date_added' => date("l dS \of F Y h:i:s A", time()));
                spClass('orders_status_historyModel')->Create($data2);
            } else {
                //创建订单
                spClass('orderModel')->create_order($status_id, $payment, $shippingselect, getIP
                    (), $this->userarr, $address, $this->code2, $this->total, $Discount);

            }
            $msg = 'OK';
            $result = array(
                'status' => 1, // 标志
                'message' => $msg, // 提示信息
                );
            echo json_encode($result); // 返回（显示）JSON结果
            //$this->jump('checkout_confirmation.html');
        } else {
            if ($_SESSION['payment_step'] == 'checkout_payment')
                $this->currency_payment = $this->return_currency($_SESSION[paypal_EC][currCodeType],
                    2);
            $this->title = T("Step 3 of 5 - Payment Information") . ":" . SITENAME;
            $this->keywords = KEYWORDS;
            $this->description = DESCRIPTION;
            $this->display("index/index_checkout_payment.html");
        }
    }

    //确认生成订单
    function CheckoutConfirmation()
    {

        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }
        $this->isCurrencies = true;
        //dump($_SESSION);
        $payment = $_SESSION['payment'];
        //echo $_SESSION['payment'];
        //echo $payment;
        //exit;
        $orders_id = $_SESSION['orders_id']; //记录当前订单ID
        $orders_sn = $_SESSION['orders_sn'];
        //echo $orders_id;
        //echo $orders_sn;
        $conditions = array("orders_sn" => $orders_sn); //检查定单是否存在
        $order = spClass('orderModel')->find($conditions);
        $this->order = $order;
        //dump($order);
        $address = spClass('address_bookModel')->find('address_book_id=' . $this->
            userarr['customers_default_address_id']);
        $address['countries_iso_code_2'] = $this->forcount($address['entry_country_id'],
            2);
        $address['entry_country_id'] = $this->forcount($address['entry_country_id']);

        //dump($address);
        $this->add = $address;

        $this->title = T("Step 4 of 5 - Order Confirmation") . ":" . SITENAME;
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        //快递费用
        foreach ($this->shippingarr as $k => $v) {
            if ($_SESSION[shipping] == $v[0]) {
                $this->selectshipping = $v;
                $shippingselect = $v;
            }
        }
        //dump($this->shippingarr);
        $cart = $this->cartarr;
        $tmpArray = array();
        $tmpArray = $cart->CartView(); // 防止在此之前数据被外部修改
        //dump($tmpArray);
        $outArray = array(); //一维数组
        // price1 是产品1的总价格
        // price2 是产品2的总价格
        // price3 是产品3的总价格
        // count  是产品的总数量
        $i = 0;
        if (is_array($tmpArray['id'])) {
            foreach ($tmpArray['id'] as $key => $val) {
                $product = spClass("productsModel")->Detail($tmpArray['pid'][$key]);
                $outArray[$i]['cartid'] = $tmpArray['id'][$key];
                $outArray[$i]['pid'] = $tmpArray['pid'][$key];
                $outArray[$i]['name'] = $tmpArray['name'][$key];
                $outArray[$i]['image'] = $product['products_image'];
                $outArray[$i]['size'] = $tmpArray['size'][$key];
                $outArray[$i]['price1'] = $tmpArray['price1'][$key];
                $outArray[$i]['price2'] = $tmpArray['price2'][$key];
                $outArray[$i]['other'] = $tmpArray['other'][$key];
                $priceview = Get_price(array(
                    'pid' => $tmpArray['pid'][$key],
                    'price' => $tmpArray['price1'][$key],
                    'price2' => $tmpArray['price2'][$key],
                    'strtype' => 1,
                    'GDcart' => 5));
                $outArray[$i]['Total'] = $priceview * $tmpArray['count'][$key];
                $outArray[$i]['count'] = $tmpArray['count'][$key];
                $data = array(
                    'orders_id' => $orders_id,
                    'products_id' => $tmpArray['pid'][$key],
                    'products_name' => $tmpArray['name'][$key],
                    'products_quantity' => $tmpArray['count'][$key],
                    'product_size' => $tmpArray['size'][$key],
                    'products_price' => $tmpArray['price1'][$key] * $this->code2['value'],
                    'final_price' => $tmpArray['price1'][$key] * $this->code2['value'] * $tmpArray['count'][$key],
                    'products_tax' => '0.0000');

                //spClass('orders_productsModel')->create($data);

                $i++;
            }

        }
        $this->tmpCaryarray = $outArray;
        //dump($outArray);
        //根据支付方式，加载不同的支付模板
        if ($payment == ALIPAY_CODE) {
            $this->payhtml = 'pay/Toalipay.html';
        }
        if ($payment == WESTERNUNION_CODE) {
            $this->payhtml = 'pay/Towesternunion.html';
        }
        if ($payment == RPPAY_CODE) {
            $this->verifyCode = md5($orders_sn . RPPAY_SITEID . RPPAY_MIYAO);
            $this->payhtml = 'pay/Torealypay.html';
        }
        if ($payment == RPPAY_M_CODE) {
            $this->verifyCode = md5($orders_sn . RPPAY_SITEID . RPPAY_MIYAO);
            $this->payhtml = 'pay/TorealypayM.html';
        }
        if ($payment == PAYPAL_EC_CODE) {
            if ($_SESSION['payment_step'] == 'checkout_payment') {
                $this->paypaltype = 'step=EC_payment';
            } else {
                $this->paypaltype = 'type=EC_Final';
            }
            $this->payhtml = 'pay/TopaypalEC.html';
        }
        if ($payment == IPS_CODE) {
            $this->payhtml = 'pay/Toipspay.html';

            //IPS支付接口版本号(*)：指定使用接口版本号，请固定使用“2.0.0”
            $Version = '2.1.0';

            //商户号(*)：IPS所提供的商户号。
            $pMerchantCode = trim(IPS_SITEID);

            //商户证书(*)：IPS商户后台merchant.ips.com.cn下载证书内字符串。
            $pMerchantKey = trim(IPS_MIYAO);

            //提交地址(*):
            $form_url = IPS_HTTP; //正式提交地址
            $this->form_url = $form_url;
            //订单交易日期(*): 客户的购物日期,日期格式：YYYYMMDDHHMISS
            $pMerchantTransactionTime = date('YmdHis');

            //商户订单编号(*): 商户提供的购物信息唯一的订单编号,长度30
            $pMerchantOrderNum = $orders_sn;

            //界面语言(*)：客户选择的支付界面显示的语言代码。EN---英文（缺省）、GB---GB中文、BIG5---BIG5中文、JP---日文、FR---法文
            $pLanguage = 'EN';

            //支付币种(*)：交易的币种代码
            $pOrderCurrency = 'RMB';

            $CNYHL = $this->currencyarr[5]['value'];
            $totalend = $this->total['price1'] + $shippingselect[1];
            $hl = $this->code2['value'];
            $symbolleft = $this->code2['symbol_left'];

            //订单实际金额(*)：购物实际总额，保留二位小数.注意:请将其它币种金额转为CNY金额，否则支付金额有误
            $pOrderAmount = number_format($totalend * $CNYHL, 2, '.', ''); //金额*汇率(0.10*6.8282)
            //echo $pOrderAmount;
            //订单显示金额：存放商户希望在IPS 平台上选择银行界面上显示给持卡人的金额。
            $pDisplayAmount = $symbolleft . $totalend * $hl;
            //echo $pDisplayAmount;
            //商品名称
            $pProductName = '';

            //商品描述
            $pProductDescription = '';

            //商户数据包：如果商户需要在交易结束后获取一些提交时参数中未定义的自定义内容，可以通过这个参数提交
            $pAttach = 'Total:' . $pDisplayAmount . ' From:' . WEBURL . ' Detail:';

            foreach ($outArray as $k => $products) {
                $pProductName .= $products['name'] . '_';
                $pAttach .= $products['name'] . '_' . $products['Total'] * $hl . '_' . $products['count'] .
                    '|';
            }


            $pProductName = html_entity_decode($pProductName);
            $pAttach = html_entity_decode($pAttach);

            if (extension_loaded('mbstring')) {
                $pProductName = ((strlen($pProductName) + mb_strlen($pProductName, 'UTF8')) / 2) >
                    255 ? mb_strcut($pProductName, 0, 251) . '...' : mb_strcut($pProductName, 0, -1);
                $pAttach = ((strlen($pAttach) + mb_strlen($pAttach, 'UTF8')) / 2) > 1024 ?
                    mb_strcut($pAttach, 0, 1020) . '...' : mb_strcut($pAttach, 0, -1);
            } else {
                $pProductName = strlen($pProductName) > 255 ? substr($pProductName, 0, 251) .
                    '...' : substr($pProductName, 0, -1);
                $pAttach = strlen($pAttach) > 1024 ? substr($pAttach, 0, 1020) . '...' : substr($pAttach,
                    0, -1);
            }
            //echo $pProductName;
            //echo $pAttach;


            //商户返回URL(*)：客户支付完成后，环迅支付会把支付结果信息发送到此参数提供的地址。
            $pSuccessReturnUrl = WEBURL . WEBDIR . spUrl('isppay', 'orderreturn');

            //预留参数1
            $pFailReturnUrl = WEBURL . WEBDIR . spUrl('isppay', 'orderreturn');

            //预留参数2
            $pErrorReturnUrl = WEBURL . WEBDIR . spUrl('isppay', 'orderreturn');

            //商户Server to Server返回地址(*)
            $pS2SReturnUrl = WEBURL . WEBDIR . spUrl('isppay', 'orderreturn');

            //交易返回接口加密方式(*)：设定环迅支付将交易结果返回时使用的防篡改策略。12-交易返回采用Md5的摘要认证方式
            $pResHashArithmetic = 12;

            //交互方式(*)：0-浏览器模式  1-浏览器+服务器模式
            $pResType = 1;

            //反欺诈验证(*)：1-启用(默认)
            $pEnableFraudGuard = 1;

            //将商户提交信息按接口文档说明写成XML格式(*)
            $pICPayReq = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><IPSReqRoot><ICPay><Version><![CDATA[$Version]]></Version><StandardPaymentReq><pMerchantOrderNum><![CDATA[$pMerchantOrderNum]]></pMerchantOrderNum><pOrderAmount><![CDATA[$pOrderAmount]]></pOrderAmount><pDisplayAmount><![CDATA[$pDisplayAmount]]></pDisplayAmount><pMerchantTransactionTime><![CDATA[$pMerchantTransactionTime]]></pMerchantTransactionTime><pOrderCurrency><![CDATA[$pOrderCurrency]]></pOrderCurrency><pLanguage><![CDATA[$pLanguage]]></pLanguage><pSuccessReturnUrl><![CDATA[$pSuccessReturnUrl]]></pSuccessReturnUrl><pFailReturnUrl><![CDATA[$pFailReturnUrl]]></pFailReturnUrl><pErrorReturnUrl><![CDATA[$pErrorReturnUrl]]></pErrorReturnUrl><pS2SReturnUrl><![CDATA[$pS2SReturnUrl]]></pS2SReturnUrl><pResType><![CDATA[$pResType]]></pResType><pResHashArithmetic><![CDATA[$pResHashArithmetic]]></pResHashArithmetic><pProductName><![CDATA[$pProductName]]></pProductName><pProductDescription><![CDATA[$pProductDescription]]></pProductDescription><pAttach><![CDATA[$pAttach]]></pAttach><pEnableFraudGuard><![CDATA[$pEnableFraudGuard]]></pEnableFraudGuard></StandardPaymentReq></ICPay></IPSReqRoot>";

            //进行base64_encode(*)
            $pICPayReqB64 = base64_encode($pICPayReq);

            //签名验证串(*)：MD5原文=商户提交信息+商户证书
            $pICPayReqHashValue = md5($pICPayReq . $pMerchantKey);

            //反欺诈验证信息：
            //持卡人信息
            $pAccID = '';
            $pAccEMail = '';
            $pAccLoginIP = '';
            $pAccLoginDate = '';
            $pAccLoginDevice = '';
            $pAccRegisterDate = '';
            $pAccRegisterDevice = '';
            $pAccRegisterIP = '';

            //帐单信息
            $pBillFName = $address['customers_firstname'];
            $pBillMName = '';
            $pBillLName = $address['customers_lastname'];
            $pBillStreet = $address['entry_street_address'];
            $pBillCity = $address['entry_city'];
            $pBillState = $address['entry_state'];
            $pBillCountry = strtolower($address['countries_iso_code_2']); //请使用国家/地区的小写二字英文代码
            $pBillZIP = $address['entry_postcode'];
            $pBillEmail = $this->userarr['customers_email_address'];
            $pBillPhone = $this->userarr['customers_telephone'];

            //产品信息
            $pProductData1 = '';
            $pProductData2 = '';
            $pProductData3 = '';
            $pProductData4 = '';
            $pProductData5 = '';
            $pProductData6 = '';
            $pProductType = '';

            //货运信息
            $pShipFName = $address['customers_firstname'];
            $pShipMName = '';
            $pShipLName = $address['customers_lastname'];
            $pShipStreet = $address['entry_street_address'];
            $pShipCity = $address['entry_city'];
            $pShipState = $address['entry_state'];
            $pShipCountry = strtolower($address['countries_iso_code_2']); //请使用国家/地区的小写二字英文代码
            $pShipZIP = $address['entry_postcode'];
            $pShipEmail = $this->userarr['customers_email_address'];
            $pShipPhone = $this->userarr['customers_telephone'];

            //使用接口版本号(*):请固定使用“1.0.0”
            $fVersion = '1.0.0';

            //指定使用验证规则库的编号,默认为1
            $pCheckRuleBaseID = '1';

            //反欺诈信息按接口文档中格式写成XML(*)
            $pAFSReq = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><IPSReqRoot><AFS><Version><![CDATA[$fVersion]]></Version><cBasicParameters><pCheckRuleBaseID><![CDATA[$pCheckRuleBaseID]]></pCheckRuleBaseID></cBasicParameters><StandardPaymentReq><cBillParameters><pBillFName><![CDATA[$pBillFName]]></pBillFName><pBillMName><![CDATA[$pBillMName]]></pBillMName><pBillLName><![CDATA[$pBillLName]]></pBillLName><pBillStreet><![CDATA[$pBillStreet]]></pBillStreet><pBillCity><![CDATA[$pBillCity]]></pBillCity><pBillState><![CDATA[$pBillState]]></pBillState><pBillCountry><![CDATA[$pBillCountry]]></pBillCountry><pBillZIP><![CDATA[$pBillZIP]]></pBillZIP><pBillEmail><![CDATA[$pBillEmail]]></pBillEmail><pBillPhone><![CDATA[$pBillPhone]]></pBillPhone></cBillParameters><cShipParameters><pShipFName><![CDATA[$pShipFName]]></pShipFName><pShipMName><![CDATA[$pShipMName]]></pShipMName><pShipLName><![CDATA[$pShipLName]]></pShipLName><pShipStreet><![CDATA[$pShipStreet]]></pShipStreet><pShipCity><![CDATA[$pShipCity]]></pShipCity><pShipState><![CDATA[$pShipState]]></pShipState><pShipCountry><![CDATA[$pShipCountry]]></pShipCountry><pShipZIP><![CDATA[$pShipZIP]]></pShipZIP><pShipEmail><![CDATA[$pShipEmail]]></pShipEmail><pShipPhone><![CDATA[$pShipPhone]]></pShipPhone></cShipParameters><cProductParameters><pProductType><![CDATA[$pProductType]]></pProductType><pProductName><![CDATA[$pProductName]]></pProductName><pProductData1><![CDATA[$pProductData1]]></pProductData1><pProductData2><![CDATA[$pProductData2]]></pProductData2><pProductData3><![CDATA[$pProductData3]]></pProductData3><pProductData4><![CDATA[$pProductData4]]></pProductData4><pProductData5><![CDATA[$pProductData5]]></pProductData5><pProductData6><![CDATA[$pProductData6]]></pProductData6></cProductParameters><cAccountParameters><pAccID><![CDATA[$pAccID]]></pAccID><pAccEMail><![CDATA[$pAccEMail]]></pAccEMail><pAccRegisterIP><![CDATA[$pAccRegisterIP]]></pAccRegisterIP><pAccLoginIP><![CDATA[$pAccLoginIP]]></pAccLoginIP><pAccRegisterDate><![CDATA[$pAccRegisterDate]]></pAccRegisterDate><pAccLoginDate><![CDATA[$pAccLoginDate]]></pAccLoginDate><pAccRegisterDevice><![CDATA[$pAccRegisterDevice]]></pAccRegisterDevice><pAccLoginDevice><![CDATA[$pAccLoginDevice]]></pAccLoginDevice></cAccountParameters></StandardPaymentReq></AFS></IPSReqRoot>";

            //对反欺诈信息进行base64_encode(*)
            $pAFSReqB64 = base64_encode($pAFSReq);

            //反欺诈签名验证串(*)：MD5原文=反欺诈信息+商户证书
            $pAFSReqHashValue = md5($pAFSReq . $pMerchantKey);
            $this->pMerchantCode = $pMerchantCode;
            $this->pICPayReqB64 = $pICPayReqB64;
            $this->pICPayReqHashValue = $pICPayReqHashValue;
            $this->pAFSReqB64 = $pAFSReqB64;
            $this->pAFSReqHashValue = $pAFSReqHashValue;

        }
        $this->display("index/index_checkout_confirmation.html");
    }

    function CheckoutSuccess()
    {
        if ($this->userarr['customers_id'] == '') {
            $this->jump(spUrl('main', 'login'));
        }
        $code = $this->spArgs('code');

        switch ($code) {
            case 'payerror':
                $paytype = T("payerror");
                break;
            case 'payys':
                $paytype = T("payys");
                break;
            case 'payyssb':
                $paytype = T("payyssb");
                break;
            case 'westernumion':
                $paytype = T("westernumion");
                break;
            default:
                $paytype = T("CheckoutSuccesSText");
        }
        $this->paytype = $paytype;


        $this->title = T("Thank You! We Appreciate your Business!") . ":" . SITENAME;
        $this->keywords = KEYWORDS;
        $this->description = DESCRIPTION;
        $this->display("index/index_checkout_success.html");
    }

    function ContactUs()
    {
        $this->iscontactus = true;

        $alias = 'Contact-Us';
        if (!$alias)
            ERROR404(1);
        $news = spClass('newsModel')->FindformAlias($alias);
        if (!$news)
            ERROR404(1);

        $this->news = $news;
        if (PL == '1')
            $this->Commentlist = spClass('news_commentsModel')->GetCommentsList($news['news_id']);
        $this->alias = $alias;
        $this->title = $news['detail']['news_title'];
        $this->keywords = $news['detail']['news_seokeywords'];
        $this->description = $news['detail']['news_seodescription'];
        $this->display("index/index_contact_us.html");
    }

    //发信给管理员
    function ContactUsSave()
    {
        //dump($this->spArgs());
        $contactname = $this->spArgs("contactname");
        $email = urldecode($this->spArgs("email-address"));
        $enquiry = urldecode($this->spArgs("enquiry"));
        $action = $this->spArgs("action");
        //                $contactname = 'DAWan';
        //                $email = 'jxfosf@qq.com';
        //                $enquiry = 'This is test';
        //                $action = 'send';
        $mail = spClass('email_templateModel');

        if ($mail->isemail($email)) {
            if ($action == 'send') {
                if ($mail->send_contact_us($email, $contactname, $enquiry)) {
                    $msg = T("Sent successfully!");
                    $status = 'y';
                } else {
                    $msg = T("Sends out the failure!");
                    $status = 'n';
                }
            } else {
                $msg = T("Sends out the failure!");
                $status = 'n';
            }
        } else {
            $msg = T("Sends out the failure!");
            $status = 'n';
        }
        $result = array(
            'status' => $status,
            'info' => $msg,
            );
        echo json_encode($result); // 返回（显示）JSON结果
    }

    function fosf()
    {
        phpinfo();
    }
}
